package admin.shell;

import java.util.HashMap;
import java.util.Map;

import admin.exceptions.CommandNotFoundException;
import admin.shell.commands.*;
import admin.ui.ProxyMediator;
import admin.util.User;

public class Shell {

	public Shell(ProxyMediator proxy) {
		this.proxy = proxy;
		this.commands = initCommands();
	}
	

	public void mainLoop() {	
		
		while (true) {
			System.out.print(PROMPT);
			
			String line = User.readString().trim();
			if (line.isEmpty())
				continue;
			
			if (line.equalsIgnoreCase("quit")) {
				System.exit(0);
			}
			
			ShellCommand command;
			try {
				command = parse(line);
				String[] parameters = line.split("\\s+");
				
				command.execute(proxy, parameters);
			} catch (CommandNotFoundException e) {
				System.out.println("Unrecognized command: " + e.getCommandName());
			}
		}
	}

	
	private ShellCommand parse(String string) throws CommandNotFoundException {
		String[] parameters = string.split("\\s+");
		String commandName = parameters[0];
				
		if (commands.containsKey(commandName)) {
			return commands.get(commandName);
		} else {
			throw new CommandNotFoundException(commandName);
		}
	}
	
	
	private Map<String, ShellCommand> initCommands() {
		Map<String, ShellCommand> commands = new HashMap<String, ShellCommand>();
		commands.put("users", new ListUsersCommand());
		commands.put("matchs", new ListMatchsCommand());
		commands.put("plugins", new ListPluginsCommand());
		commands.put("user", new UserDetailsCommand());
		commands.put("start", new StartCommand());
		commands.put("stop", new StopCommand());
		commands.put("create", new CreateCommand());
		commands.put("delete", new DeleteCommand());
		commands.put("edit", new EditCommand());
		commands.put("help", new HelpCommand());
		
		return commands;
	}
	
	private ProxyMediator proxy;
	private Map<String, ShellCommand> commands;
	
	
	private static final String PROMPT = "\n$ ";
}
